package com.springboot.base.config;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayConfig;
import com.alipay.api.DefaultAlipayClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@Data
public class AlipayClientConfig {

    public static final String SIGN_TYPE = "RSA2";
    public static final String ENCRYPT_TYPE = "AES";
    public final static String ALIPAY_JSON = "json";
    public final static String GBK = "gbk";
    public final static String UTF8 = "utf-8";

    private static final String GATEWAY = "https://openapi.alipay.com/gateway.do";
    @Value("${alipay.certPath}")
    private String certPath;

    @Value("${alipay.app.id}")
    private String appId;
    @Value("${alipay.app.private.key}")
    private String appPrivateKey;
    @Value("${alipay.appCertPath}")
    private String appCertPath;


    @Value("${alipay.alipayPublicCertPath}")
    private String alipayPublicCertPath;
    @Value("${alipay.rootCertPath}")
    private String rootCertPath;

    @Value("${alipay.aes.key}")
    private String alipayAesKey;
//    @Value("${alipay.notify.url}")
//    private String notifyUrl;

    private AlipayClient alipayClient = null;

    /**
     * 支付宝客户端
     *
     * @return
     */
    @Bean(name = "alipayClient")
    public AlipayClient getAlipayClient() {
        if (alipayClient == null) {
            synchronized (AlipayClientConfig.class) {
                if (alipayClient == null) {
                    AlipayConfig alipayConfig = new AlipayConfig();
                    //设置网关地址
                    alipayConfig.setServerUrl(GATEWAY);
                    //设置应用ID
                    alipayConfig.setAppId(appId);
                    //设置应用私钥
                    alipayConfig.setPrivateKey(appPrivateKey);
                    //设置应用公钥证书路径
                    alipayConfig.setAppCertPath(appCertPath);
                    //设置支付宝公钥证书路径
                    alipayConfig.setAlipayPublicCertPath(alipayPublicCertPath);
                    //设置支付宝根证书路径
                    alipayConfig.setRootCertPath(rootCertPath);
                    //设置请求格式，固定值json
                    alipayConfig.setFormat(ALIPAY_JSON);
                    //设置字符集
                    alipayConfig.setCharset(UTF8);
                    //设置签名类型
                    alipayConfig.setSignType(SIGN_TYPE);
                    //构造client
                    try {
                        alipayClient = new DefaultAlipayClient(alipayConfig);
                    } catch (AlipayApiException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return alipayClient;
    }
}
